package com.situ.lession1226.controller;

import com.situ.lession1226.interceptor.LoginInterceptor;
import com.situ.lession1226.model.Account;
import com.situ.lession1226.service.AccountService;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Map;


@Controller
public class AdminController {
    private AccountService accountService;

    @Autowired
    public void setUserService(AccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * 跳转到后台管理系统
     */
    @GetMapping("/admin1")
    public String admin1() {
        return "admin/admin1";
    }

    @GetMapping("/admin2")
    public String admin2() {
        return "admin/admin2";
    }
    @GetMapping("/admin3")
    public String admin3() {
        return "admin/admin3";
    }
    /**
     * 跳转到欢迎页
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "admin/welcome";
    }

    /**
     * 跳转到登录页
     */
    @GetMapping("/admin/login")
    public String login() {
        return "admin/login";
    }

    @GetMapping("/admin/register")
    public String register() {
        return "admin/register";
    }

    /**
     * 后台登录验证
     */
    @PostMapping(value = "/admin/login", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> login(Account account, String captcha, HttpSession session) {
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (!captcha.equalsIgnoreCase(sessionCaptcha)) {
            return Map.of("success", false, "error", "验证码不正确");
        }
        String username= account.getUsername();
        //到数据库中查询用户
        Account dbAccount = accountService.findByUsername(username);
        if (dbAccount == null) {
            return Map.of("success", false, "error", "无此用户");
        }

        //对用户输出的用户名进行md5加密
//        String str = user.getPassword() + "{" + user.getUserName() + "}";
//        String encrypted = DigestUtils.md5DigestAsHex(str.getBytes(StandardCharsets.UTF_8));


        String encrypted= account.getPassword();
        if (dbAccount.getPassword().equals(encrypted)) {//密码匹配
            if(dbAccount.getRole().equals(account.getRole())) {
                //登录成功，则将用户实体放入到会话域中
                session.setAttribute(LoginInterceptor.LOGIN_USER_KEY, account);
                return Map.of("success", true,"role", account.getRole());
            }else {
                return Map.of("success",false,"error","用户身份不正确");
            }
        } else {
            return Map.of("success", false, "error", "用户名或密码不正确");
        }
    }

    /**
     * 退出登录，注销功能
     */
    @GetMapping("/admin/logout")
    public String logout(HttpSession session) {
        //移除session中存储的认证数据
        session.removeAttribute(LoginInterceptor.LOGIN_USER_KEY);
        //返回值以redirect:为前缀，则表示重定向
        return "redirect:/admin1";
    }

    /**
     * 生成验证码图片
     */
    @GetMapping("/admin/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);

        //清除缓存
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);

        request.getSession().setAttribute("captcha", captcha.text().toLowerCase());
        captcha.out(response.getOutputStream());
    }
}
